/*
 * TCSS 558
 * Distributed HashMap
 * Fall 2013
 * James Marquardt
 * Matt Adams
 * Justin Wong
 */
package tools;

public final class CheckArgument {
    
    private static final int MAX_PORT_NUMBER = 65535;
    
    private CheckArgument() {
        //prevent instantiation
    }
    
    public static int getValidPortFromString(final String portString) {
        int result = 0;
        try {
            result = Integer.parseInt(portString);
        } catch (NumberFormatException e) {
            Log.err("Not valid integer for port number: " + e.getMessage());
            errorClose();
        }
        if (!isValidPort(result)) {
            Log.err("Port number must be between 1 and 65535, inclusive.");
            errorClose();
        }
        return result;
    }
    
    public static boolean isValidPort(final int port) {
        boolean result = true;
        if (port < 1 || port > MAX_PORT_NUMBER) {
            Log.err("Port number must be between 1 and 65535, inclusive.");
            result = false;
        }
        return result;
    }
    
    private static void errorClose() {
        Log.out("Program closed.");
        System.exit(1);
    }
    
    /**
     * Checks if this ID is in the interval determined by the two given IDs.
     * Neither of the boundary IDs is included in the interval.
     * 
     * @param checkID ID being checked for containment in a given interval.
     * @param fromID Lower bound of interval.
     * @param toID Upper bound of interval.
     * @return If the provided ID is included in the given interval.
     */
    public static boolean isInInterval(final int checkID, final int fromID, final int toID) {
        boolean result = false;
        
        // both interval bounds are equal -> calculate out of equals
        if (fromID == toID) {
            // every ID is contained in the interval except of the two bounds
            result = (checkID != fromID);
        } else if (fromID < toID) {
            // interval does not cross zero -> compare with both bounds
            result = (checkID > fromID && checkID <= toID);
        } else {
            // interval crosses zero -> split interval at zero
            result = (checkID > fromID) || (checkID <= toID);
        }
        return result;
    }

}
